package util

import (
	"database/sql"

	_ "github.com/lib/pq"
)

const port string = "5432"
const dbname string = "postgres"
const user string = "postgres"
const driverName string = "postgres"
const password string = "123456"
const sslmode string = "disable"

//var db *sql.DB

////获取*sql.DB
//func GetDb() *sql.DB {
//	return db
//}

////初始化Db
//func InitDb() {
//	sourceString := "user=" + user + " password=" + password + " dbname=" + dbname + " sslmode=" + sslmode
//	db2, err := sql.Open(driverName, sourceString)
//	db = db2
//	logs.Print("InitDb Success")
//	if err != nil {
//		fmt.Println("From:InitDb:---", err.Error())
//	}
//}

////关闭数据库
//func CloseDb(db *sql.DB) {
//	err := db.Close()
//	if err != nil {
//		fmt.Println("From: CloseDb:---", err.Error())
//	}
//}

var dbQueue chan *sql.DB

func Init(queue chan *sql.DB) {
	dbQueue = queue
}
func openDB() *sql.DB {
	return <-dbQueue
}
func closeDB(db *sql.DB) {
	dbQueue <- db
}
func Exec(sql string, args ...interface{}) (sql.Result, error) {
	db := openDB()
	defer closeDB(db)

	stmt, err := db.Prepare(sql)
	defer stmt.Close()
	if err != nil {
		return nil, err
	}
	result, err := stmt.Exec(args...)
	if err != nil {
		return nil, err
	}

	return result, nil

}

func Query(sql string, args ...interface{}) (*sql.Rows, *sql.Stmt, error) {
	db := openDB()
	defer closeDB(db)

	stmt, err := db.Prepare(sql)
	if err != nil {
		return nil, nil, err
	}
	rows, err := stmt.Query(args...)
	if err != nil {
		return nil, nil, err
	}

	return rows, stmt, nil

}
